<?php



namespace Pay\Controller;

use Think\Controller;
use Think\PageController;
use Think\UploadFile;


class IndexPCController extends Controller
{


    public function index()
    {
        $this->display();
    }
    public function dingdan()
    {
    	$this->display();
    }
     public function teacherpay()
    {
        $map['unit']=$_SESSION['oc_home']['unit'];
        if($_SESSION['oc_home']['group']=='4'){
            $map['class_id'] = $_SESSION['oc_home']['class'];
        }
        $map['pay_state']=0;
        
        $totalCount = M('core_pay_bill_view')->where($map)->count('distinct(uid)');

        $page = new \Think\Page($totalCount,10);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list = M('core_pay_bill_view')->where($map)->limit($limit)->group('uid')->order('id desc')->select();
          foreach ($list as $key => $value) {
            $list[$key]['amount'] =      M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('amount');
            $list[$key]['last_amount'] = M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('last_amount');
            $list[$key]['amount'] = $list[$key]['amount']- $list[$key]['last_amount'];
        } 
        $this->assign('_page',$page->show());
        
        $count=count($list);
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->display();
    }

 //缴费统计
 public function principalpay()
 {
     //设置编码格式
     header("Content-type: text/html; charset=utf-8");
     $this->assign('go',I('go'));
     //查询关键字进行搜索。
     if(I('nickname')){    
         $nickname = I('nickname');
         $map['nickname'] = array('like','%'.$nickname.'%');
         $this->assign('nickname',$nickname);
     }

     //查询班级
     if(I('classlist')){  
         $map['class_id'] = I('classlist');
     }

     //查询学校
     if(I('units')){
         $map['unit'] =  I('units');
     }
     
     //按时间查询条件
     if(I('create_time')){
         $map['create_time'] = array(between,array(strtotime(I('create_time')),strtotime(I('create_time').'23:59:58')));
     }

     //获取角色
     $group_id = $_SESSION['oc_home']['group'];

     //学校类型
     if($group_id == 6){
         $con['pid'] = $_SESSION['oc_home']['unit'];
         
         $this->units = M('core_unit')->where($con)->field('id','title')->select();
     }else{
         $con['id'] = $_SESSION['oc_home']['unit'];

         $this->units = M('core_unit')->where($con)->field('id','title')->select();

     }

     //班级类型
     $map['unit']=$_SESSION['oc_home']['unit'];
     $this->classlist=M('core_class')->where('unit='.$_SESSION['oc_home']['unit'])->select();

     switch (I('go')) {
         case '1':
             $map['pay_state'] = I('go');
             break;
         case '0':
             $map['pay_state'] = I('go');
             break;
         default:
             $map['pay_state'] = array('in','1,0');
             break;
     }
     
     //统计已缴费条数
     $map1['pay_state'] = "1";
     $this->succ = M('core_pay_bill_view')->where($map)->where($map1)->count('distinct(uid)');

     //统计未缴费条数
     $map2['pay_state'] = "0";
     $this->error = M('core_pay_bill_view')->where($map)->where($map2)->count('distinct(uid)');
     
     //统计总条数
     $map3['pay_state'] = array('in','1,0');
     $this->count = M('core_pay_bill_view')->where($map)->where($map3)->count('distinct(uid)');

     //分页查询
     $totalCount = M('core_pay_bill_view')->where($map)->count();
     $page = new \Think\Page($totalCount,10);
     $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
     $list = M('core_pay_bill_view')->where($map)->limit($limit)->order('id desc')->group('uid')->select();
       foreach ($list as $key => $value) {
            $list[$key]['amount'] =      M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('amount');
            $list[$key]['last_amount'] = M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('last_amount');
            $list[$key]['amount'] = $list[$key]['amount']- $list[$key]['last_amount'];
        }
     $this->assign('_page',$page->show());
     $this->assign('list',$list);
     $this->display();
 }

 //订单统计
 public function principalorder()
 {
     //查询关键字进行搜索。
     if(I('nickname')){    
         $nickname = I('nickname');
         $map['nickname'] = array('like','%'.$nickname.'%');
         $this->assign('nickname',$nickname);
     }

     //查询学校
     if(I('units')){  
         $map['class_id'] = I('units');
     }

     //查询班级
     if(I('classlist')){  
         $map['class_id'] = I('classlist');
     }

     //获取角色
     $group_id = $_SESSION['oc_home']['group'];

     //学校类型
     if($group_id == 6){
         $con['pid'] = $_SESSION['oc_home']['unit'];
         $this->units = M('core_unit')->where($con)->field('id','title')->select();
     }else{
         $con['id'] = $_SESSION['oc_home']['unit'];
         $this->units = M('core_unit')->where($con)->field('id','title')->select();
     }

     //班级类型
     $map['unit']=$_SESSION['oc_home']['unit'];
     $this->classlist=M('core_class')->where('unit='.$_SESSION['oc_home']['unit'])->select();

     //订单查询
     $map['paystate']=array('in','1,0');
     $list=M('core_pay_order_view')->where($map)->select();
     //统计订单条数
     $this->count=count($list);
     $this->assign('list',$list);
     $this->display();
 }

 //账单统计
 public function principalzd()
 {
     if(I('nickname')){    //查询关键字进行搜索。
         $nickname = I('nickname');
         $map['nickname'] = array('like','%'.$nickname.'%');
         $this->assign('nickname',$nickname);
     }
     if(I('classlist')){  
         $map['class_id'] = I('classlist');

     }

     //获取角色
     $group_id = $_SESSION['oc_home']['group'];
     
     //学校类型
     if($group_id == 6){
         $con['pid'] = $_SESSION['oc_home']['unit'];
         $this->units = M('core_unit')->where($con)->field('id','title')->select();
     }
     else{
         $con['id'] = $_SESSION['oc_home']['unit'];
         $this->units = M('core_unit')->where($con)->field('id','title')->select();

     }

     //班级类型
     $map['unit']=$_SESSION['oc_home']['unit'];
     $this->classlist=M('core_class')->where('unit='.$_SESSION['oc_home']['unit'])->select();
     
     $map['unit']=$_SESSION['oc_home']['unit'];
     $list=M('core_pay_order_view')->where($map)->select();

     //$units=M('core_unit')->where('id='.$_SESSION['oc_home']['unit'])->select();
     //$classlist=M('core_class')->where('unit='.$_SESSION['oc_home']['unit'])->select();
   
     $this->assign('list',$list);
     //$this->assign('units',$units);
     //$this->assign('classlist',$classlist);
     $this->display();
 }
    //管理费上次结余
    public function mlast_amount($stu_id,$mitem)
    {
        $mamount = unserialize($mitem['mmark']);
        for($i=$mitem['mstart_month'];$i<=$mitem['mend_month'];$i++){
            $mcon['uid'] = $stu_id;
            $mcon['month'] = date('Y-',$mitem['create_time']).$i;
            $mcon['status'] = array('neq',1);
            $mcount = M('core_attendance_detail')->where($mcon)->count();
            if($mcount>1){
                $total+=$mamount['amount']/=2;
            }
        }
        $data['mlstate'] = 1;
        $result  = M('core_pay_item')->where("id=".$mitem['id'])->save($data);
        if($total){
            return $total;
        }else{
            return 0;
        }
    }
    //餐费上次结余
    public function flast_amount($stu_id,$fitem)
    {
        // dump($mark);exit;
        $famount = unserialize($fitem['fmark']);
        for($i=$fitem['fstart_month'];$i<=$fitem['fend_month'];$i++){
            $fcon['uid'] = $stu_id;
            $fcon['status'] = array('neq',1);
            $fcon['month'] = date('Y-',$fitem['create_time']).$i;
            $acount = M('core_attendance_detail')->where($fcon)->count();
            $total += $famount['amount'] *= $acount;
        }
        $data['flstate'] = 1;
     
        $result  = M('core_pay_item')->where("id=".$fitem['id'])->save($data);
        if($total){
            return $total;
        }else{
            return 0;
        }
    }
    //智能生成账单
    public function financepay()
    {
        if(IS_POST)
        {
            if(!I('post.ititle')) $this->error('请输入账单名称!');
            $map['unit_id']=$_SESSION['oc_home']['unit'];
            $map['group_id'] = 5 ;
             
            
            $stulist =M('core_userinfo_view')->where($map)->select();

            $model_object = D('core_pay_bill');
            //上次管理费结余信息
            $con['unit'] = $_SESSION['oc_home']['unit'];
            $mcon['mlstate'] = 0;
            $mitem = M('core_pay_item')->where($mcon)->where($con)->find();
            //上次餐费结余信息
            $fcon['flstate'] = 0;
            $fitem = M('core_pay_item')->where($fcon)->where($con)->find();
            //生成缴费项目
            $map['unit']=$_SESSION['oc_home']['unit'];
            $list=M('core_unit_paytype')->where($map)->select();
            $this->assign('list',$list);
            $item_id = $this->build_item();
            $batch = md5(I("ititle").time());
            foreach (I('ylist') as $ck => $cv) {
                $tmp = explode(',',$cv);
                $detail .= $tmp[3].":".$tmp[2].";";
            }
            foreach ($stulist as $sk => $sv) 
            {
                foreach (I('ylist') as $ck => $cv) {
                    $tmp = explode(',',$cv);
                    $tbdata['item_c'] = $tmp[0];
                    switch ($tmp[1]) {
                        case 'manage':
                            $tbdata['amount'] = $tmp[2]*(I('mend_month')-I('mstart_month')+1);
                            //管理费结余
                            if($mitem){
                                $tbdata['last_amount'] = $this->mlast_amount($sv['uid'],$mitem);
                            }
                            // $tbdata['detail'] = $tbdata['item_c'].":".$tbdata['amount'].".";
                            break;
                        case 'food':
                            $tbdata['amount'] = $tmp[2]*(I('fend_month')-I('fstart_month')+1)*22; //默认一月实到22天
                            //餐费结余
                            if($fitem){
                                $tbdata['last_amount'] = $this->flast_amount($sv['uid'],$fitem);
                                
                            }
                            // $tbdata['detail'] = $tbdata['item_c'].":".$tbdata['amount'].".";
                            break;
                    }
                    $tbdata['unit'] = $_SESSION['oc_home']['unit'];
                    $tbdata['uid'] = $sv['uid'];
                    $tbdata['detail'] = $detail;
                    $tbdata['create_time'] = time();
                    $tbdata['status'] = 1;
                    $tbdata['pay_state'] = 0;
                    $tbdata['item'] = $item_id;
                    $tbdata['batch'] = $batch;
                    $bdata[] = $tbdata;
                }
            }
            
            $result = M('core_pay_bill_tmp')->addAll($bdata);
            if($result){
                $_SESSION['last_batch'] = $batch;
                $_SESSION['ylist'] = serialize(I('ylist'));
                // dump(I('ylist'));exit;
                $this->success('生成成功，正在跳转预览页面……',U('bill_tmp'));

            }
        }else{ 
            $map['unit']=$_SESSION['oc_home']['unit'];
            $list=M('core_unit_paytype')->where($map)->select();
            $this->assign('list',$list);
            
            $id =M('core_pay_bill_view')->Max('id');
            $batch =M('core_pay_bill_view')->where('id='.$id)->getField('batch');
            $bmap['unit']=$_SESSION['oc_home']['unit'];
            $bmap['status'] =1;
            $bmap['batch']=$batch;
            $totalCount = M('core_pay_bill_view')->where($bmap)->count('distinct(uid)');
            
            $page = new \Think\Page($totalCount,2);
            $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
       
              $llist=M('core_pay_bill_view')->where($bmap)->limit($limit)->group('uid')->select();
        foreach ($llist as $key => $value) {
                $llist[$key]['amount'] =      M('core_pay_bill_view')->where($bmap)->where('uid = '.$value['uid'])->sum('amount');
                $llist[$key]['last_amount'] = M('core_pay_bill_view')->where($bmap)->where('uid = '.$value['uid'])->sum('last_amount');
                $llist[$key]['amount'] = $llist[$key]['amount'] - $llist[$key]['last_amount'];
                } 
          
         $this->assign('_list',$llist);
         $this->assign('_page',$page->show());
            $this->display();
        }

    }
    //账单预览
    public function bill_tmp()
    {
        // if(IS_POST){
        //     $con['batch'] = $_SESSION['last_batch'];
        //     $tmp = M('core_pay_bill_tmp')->where($con)->select();
        //     $result = M('core_pay_bill')->addAll($tmp);
        //     if($result){
        //         $this->success('生成成功',U('bill'));
        //     }else{
        //         $this->error('生成失败');
        //     }
        // }else{
            //单位列表
            if(I('class_id')){
                $bcon['class_id'] = I('class_id');
            }
            if(I('nickname')){
                $bcon['nickname'] = array('like','%'.I('nickname').'%');
            }
            $con['id'] = $_SESSION['oc_home']['unit'];
            $ccon['unit'] = $_SESSION['oc_home']['unit'];
            $ulist = M('core_unit')->where($con)->select();
            $clist = M('core_class')->where($ccon)->select();
            $this->assign('ulist',$ulist);
            $this->assign('clist',$clist);
            $bcon['batch'] = $_SESSION['last_batch'];
            $bill_tmp = M('core_pay_bill_tmp_view')->where($bcon)->group('uid')->order('id desc')->select();

            //子账单总金额
            foreach ($bill_tmp as $key => $value) {
                $bill_tmp[$key]['total'] = M('core_pay_bill_tmp_view')->where($bcon)->where('uid = '.$value['uid'])->sum('total');
                $bill_tmp[$key]['last_amount'] = M('core_pay_bill_tmp_view')->where($bcon)->where('uid = '.$value['uid'])->sum('last_amount');
                $bill_tmp[$key]['detail']= M('core_pay_bill_tmp_view')->where($bcon)->where('uid = '.$value['uid'])->getField('item_c,ctitle,amount',true);
            }
            foreach (unserialize($_SESSION['ylist']) as $key => $value) {
                $ylist[$key] = explode(',',$value);
            }
            $this->assign('ylist',$ylist);
            $this->assign('_list',$bill_tmp);
            $this->display();
        // }
    }



    //单个/批量修改金额
    public function updateItem_c()
    {
        if(I('uid')){
            //单个用户修改
            foreach ($_POST as $key => $value) {
                if($key!='uid'){
                    $con['uid'] = I('uid');
                    $con['item_c'] = $key;
                    $con['batch'] = $_SESSION['last_batch'];
                    $data['amount'] = $value;
                    $result = M('core_pay_bill_tmp')->where($con)->save($data);
                    if(!$result){
                        echo "修改失败";
                    }
                }
            }
        }else{
            //批量修改金额
            $con['item_c'] = I('item_c');
            $con['batch'] = $_SESSION['last_batch'];
            $data['amount'] = I('amount');
            $result = M('core_pay_bill_tmp')->where($con)->save($data);
            if(!$result){
                echo "修改失败";
            }
        }
        $this->success('修改成功',U('bill_tmp'));
    }
    //单个/批量修改金额bill表
    public function updateItem_c_bill()
    {
        if(I('uid')){
            //单个用户修改
            foreach ($_POST as $key => $value) {
                if($key!='uid'&&$value!=''){
                    $con['uid'] = I('uid');
                    $con['item_c'] = $key;
                    $con['batch'] = $_SESSION['batch'];
                  
                    $data['amount'] = $value;
                    $result = M('core_pay_bill')->where($con)->save($data);
                    if(!$result){
                        echo "修改失败";
                    }
                }
            }
        }else{
            //批量修改金额
            $con['item_c'] = I('item_c');
            $con['batch'] = $_SESSION['batch'];
            $data['amount'] = I('amount');
            $result = M('core_pay_bill')->where($con)->save($data);
            if(!$result){
                echo "修改失败";
            }
        }
        $this->success('修改成功',U('financebill'));
    }
    //下载结余模版
    public function last_output(){
       
       import('Org.Util.PHPExcel');
       $resultPHPExcel = new \PHPExcel(); //一定要加跟杠，不然报错 
       //设置参数 
       //设值
       // $data['type'] = $_SESSION['type'];
       
       if(I('class_id')){
           $bcon['class_id'] = I('class_id');
       }
       if(I('nickname')){
           $bcon['nickname'] = array('like','%'.I('nickname').'%');
       }
       $bcon['batch'] = $_SESSION['last_batch'];
       $data = M('core_pay_bill_tmp_view')->where($bcon)->group('uid')->order('id desc')->select();
       // dump($data);exit;
       $resultPHPExcel->getActiveSheet()->setCellValue('A1', '请勿修改');
       $resultPHPExcel->getActiveSheet()->setCellValue('B1', '姓名'); 
       $resultPHPExcel->getActiveSheet()->setCellValue('C1', '班级');
       foreach (unserialize($_SESSION['ylist']) as $k => $v) {
           $a = explode(',',$v);
           if($a[1]=="manage"){
               $resultPHPExcel->getActiveSheet()->setCellValue('D1', $a[3].'|'.$a[0]); 
           }
           if($a[1]=="food"){
               $resultPHPExcel->getActiveSheet()->setCellValue('E1', $a[3].'|'.$a[0]); 
           }

       }
       $resultPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth('2');  
       $resultPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth('20');  
       $resultPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth('20');  
       $resultPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth('20');  
       $resultPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth('20');  
       $i = 2; 

       foreach($data as $item){ 
           $resultPHPExcel->getActiveSheet()->setCellValue('A'.$i," ".$item['uid']); 
           $resultPHPExcel->getActiveSheet()->setCellValue('B'.$i,$item['nickname']); 
           $resultPHPExcel->getActiveSheet()->setCellValue('C'.$i," ".$item['class_title']); 
       $i ++; 
       }
       // dump("d");exit;
       //设置导出文件名 
       $outputFileName = '结余.xls'; 
       $xlsWriter = new \PHPExcel_Writer_Excel5($resultPHPExcel); 
       //ob_start(); ob_flush(); 
       header("Content-Type: application/force-download"); 
       header("Content-Type: application/octet-stream"); 
       header("Content-Type: application/download"); 
       header('Content-Disposition:inline;filename="'.$outputFileName.'"'); 
       header("Content-Transfer-Encoding: binary"); 
       header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); 
       header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
       header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
       header("Pragma: no-cache"); 
       $xlsWriter->save( "php://output" );
       // dump("s");exit;
     }
     //导入结余
    public function last_input()
    {
         $upload = new UploadFile();// 实例化上传类
         $upload->maxSize  = 3145728 ;// 设置附件上传大小
         $upload->allowExts  = array('xls','xlsx');// 设置附件上传类型
         if (!file_exists('./Uploads/Last/'.date('Ymd').'/')){ 
             mkdir('./Uploads/Last/'.date('Ymd').'/'); 
         }
         $upload->savePath =  './Uploads/Last/'.date('Ymd').'/';// 设置附件上传目录
         if(!$info = $upload->upload()) {// 上传错误提示错误信息
             $this->error($upload->getErrorMsg());
         }else{// 上传成功 获取上传文件信息
             $info =  $upload->getUploadFileInfo();
         }
        $info[0]['savepath']=substr($info[0]['savepath'], 1); 
        $filename = $info[0]['savepath'].$info[0]['savename'];
        $this->showExcel($filename);
       
    }
     //数据管理-因为导入的文件，所以需要一个文件类来打开该文件
     public function showExcel($filename)
     {
         header('Content-type:text/html;charset=utf8');
         import("Org.Util.PHPExcel");
         import("Org.Util.PHPExcel.Reader.Excel5");
         //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
         //创建PHPExcel对象，注意，不能少了\
         $PHPExcel=new \PHPExcel();
         //如果excel文件后缀名为.xls，导入这个类
         import("Org.Util.PHPExcel.Reader.Excel2007");
         $PHPReader=new \PHPExcel_Reader_Excel5();
         //载入文件
         $PHPExcel=$PHPReader->load('.'.$filename);
         //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
         $currentSheet=$PHPExcel->getSheet(0);
         //获取总列数
         $allColumn=$currentSheet->getHighestColumn();
         //获取总行数
         $allRow=$currentSheet->getHighestRow();
         //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
         for($currentRow=2;$currentRow<=$allRow;$currentRow++){
             //从哪列开始，A表示第一列
             for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                 //数据坐标
                 $address=$currentColumn.$currentRow;
                 //读取到的数据，保存到数组$arr中
                 $arr[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
             }
         }
         /////存入临时表
         $TempModel = D('core_pay_bill_tmp');
         $TempModel->startTrans();
        foreach ($arr as $key => $value) {
            $con['uid'] = $value['A'];
            $con['batch'] = $_SESSION['last_batch'];

            $mcon['item_c'] = explode('|',$currentSheet->getCell('D1')->getValue())[1];
            $result = $TempModel->where($con)->where($mcon)->setInc('last_amount',$value['D']);

            $fcon['item_c'] = explode('|',$currentSheet->getCell('E1')->getValue())[1];
            $result2 = $TempModel->where($con)->where($fcon)->setInc('last_amount',$value['E']);
            if($result&&$result2){
                $TempModel->commit();
            }else{
                $TempModel->rollback();
                $this->error('导入失败');
            }
        }
        $this->success('导入成功，请仔细检查数据……',U('bill_tmp'));
         
     }
     //生成账单
     public function create_bill()
     {

        $tmp = M('core_pay_bill_tmp')->where("batch = '".$_SESSION['last_batch']."'")->select();
        
        if(M('core_pay_bill')->addAll($tmp)){
           
            $this->success('生成成功',U('financepay'));
        }else{
           
                $this->error('生成失败');
            }
     }
    //生成缴费项目
    public function build_item()
    {
        $data['unit'] = $_SESSION['oc_home']['unit'];
        $data['title'] = I("ititle");
        $data['mstart_month'] =I("mstart_month");
        $data['mend_month'] = I("mend_month");
        $data['fstart_month'] =I("fstart_month");
        $data['fend_month'] = I("fend_month");
        $data['status'] = 1;
        $data['remark'] = I('remark');
        $data['create_time'] = time();
        $data['start_date'] = strtotime(I("start_date"));
        $data['end_date'] = strtotime(I("end_date"));

        foreach (I('ylist') as $k => $v) {
            $tmp = explode(',',$v);
            switch ($tmp[1]) {
                case 'manage':
                    $mmark['mark'] = $tmp[1];
                    $mmark['amount'] = $tmp[2];
                    $data['mmark'] = serialize($mmark);
                    $m=1;
                    break;
                case 'food':
                    $fmark['mark'] = $tmp[1];
                    $fmark['amount'] = $tmp[2];
                    $data['fmark'] = serialize($fmark);
                    $f=1;
                    break;
            }
            if($m==1){
                $data['mlstate'] = 0;
            }else{
                $data['mlstate'] = 2;
            }
            if($f==1){
                $data['flstate'] = 0;
            }else{
                $data['flstate'] = 2;
            }

        }
        $result = M('core_pay_item')->add($data);
        if(!$result){
            return 0;
        }
        return $result;
    }


    public function shanchu()
    {
        $aa['status']=-1;
        $list=M('core_pay_bill_view')->where('id='.I('id'))->save($aa);
        $this->success('删除成功',U('financepay'));
    }
    public function financepay1()
    {
        if(I('nickname')){    //查询关键字进行搜索。
            $nickname = I('nickname');
            $map['nickname'] = array('like','%'.$nickname.'%');
            $this->assign('nickname',$nickname);
        }
        $id =M('core_pay_bill_view')->Max('id');
        $batch =M('core_pay_bill_view')->where('id='.$id)->getField('batch');
        $map['unit']=$_SESSION['oc_home']['unit'];
        $map['status'] =1;
        $map['batch']=$batch;
        $map1['pay_state']=1;
        $map2['pay_state']=0;
        $totalCount = M('core_pay_bill_view')->where($map)->count('distinct(uid)');
        $page = new \Think\Page($totalCount,2);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list=M('core_pay_bill_view')->where($map)->group('uid')->limit($limit)->select();
        foreach ($list as $key => $value) {
                $list[$key]['amount'] =      M('core_pay_bill_view')->where($map)->where('uid = '.$value['uid'])->sum('amount');
                $list[$key]['last_amount'] = M('core_pay_bill_view')->where($map)->where('uid = '.$value['uid'])->sum('last_amount');
                $list[$key]['amount'] = $list[$key]['amount'] - $list[$key]['last_amount'];
                }
        $succ=M('core_pay_bill_view')->where($map)->where($map1)->count('distinct(uid)');
        $eroo=M('core_pay_bill_view')->where($map)->where($map2)->count('distinct(uid)');
        $this->assign('_page',$page->show());
        $count=count($list);
        $this->assign('list',$list);
        $this->assign('count',$count);
        $this->assign('succ',$succ);
        $this->assign('eroo',$eroo);
        $this->display();
    }
    //财务人员管理
    public function financeorder()
    {
        if(I('nickname')){    //查询关键字进行搜索。
            $nickname = I('nickname');
            $map['nickname'] = array('like','%'.$nickname.'%');
            $this->assign('nickname',$nickname);
        }

        $map['unit'] = I('unit');
        $map['class_id'] = I('class_id');
        $params = array(
            'unit'=>I('unit'),
            'class_id'=>I('class_id')
        );
        $this->assign('params',$params);
        // 学校类型
        $this->units=M('core_unit')->where('id='.$_SESSION['oc_home']['unit'])->select();
        //班级类型
        $this->classlist=M('core_class')->where('unit='.$_SESSION['oc_home']['unit'])->select();

        //统计总订单数
        $this->count = M('core_pay_order_view')->where($map)->count();

        $totalCount = M('core_pay_order_view')->where($map)->count();
        $page = new \Think\Page($totalCount,5,$params);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list=M('core_pay_order_view')->where($map)->limit($limit)->select();
        $this->assign('_page',$page->show());
        $this->assign('list',$list);
        $this->display();
    }
    // public function financeorder()
    // {
    //     if(I('nickname')){    //查询关键字进行搜索。
    //         $nickname = I('nickname');
    //         $map['nickname'] = array('like','%'.$nickname.'%');
    //         $this->assign('nickname',$nickname);
    //     }
    //     $map['unit']=$_SESSION['oc_home']['unit'];
    //     $units=M('core_unit')->where('id='.$_SESSION['oc_home']['unit'])->select();
    //     $classlist=M('core_class')->where('unit='.$_SESSION['oc_home']['unit'])->select();
    //     $map1['paystate']=1;
    //     $map2['paystate']=0;
    //     $js=M('core_pay_order')->where($map)->select();
    //     $list=M('core_pay_order')->where($map)->where($map1)->select();
    //     $count=count($js);
    //     $ad=M('core_pay_order')->where($map)->where($map2)->select();
    //     foreach ($list as $key => $value) {
    //         $data=M('core_userinfo_view')->where('uid='.$value['uid'])->getField('nickname');
    //         $fff=M('core_userinfo_view')->where('uid='.$value['uid'])->getField('class_title');
    //         $list[$key]['lname']=$data;
    //         $list[$key]['class']=$fff;
    //     }
    //     foreach ($ad as $key => $value) {
    //         $data=M('core_userinfo_view')->where('uid='.$value['uid'])->getField('nickname');
    //         $fff=M('core_userinfo_view')->where('uid='.$value['uid'])->getField('class_title');
    //         $ad[$key]['lname']=$data;
    //         $ad[$key]['class']=$fff;
    //     }
    //     $get=M('core_pay_order')->where('id='.I('tid'))->find();
    //     $this->assign('list',$list);
    //     $this->assign('ad',$ad);
    //     $this->assign('count',$count);
    //     $this->assign('units',$units);
    //     $this->assign('classlist',$classlist);
    //     $this->assign('ho',$ho);
    //     $this->assign('get',$get);
    //     $this->display();
    // }
    public function financebill()
    {
        if(I('class_id')){
            $map['class_id'] = I('class_id');
        }
        if(I('nickname')){
            $map['nickname'] = array('like','%'.I('nickname').'%');
        }
        $con['id'] = $_SESSION['oc_home']['unit'];
        $ccon['unit'] = $_SESSION['oc_home']['unit'];
        $ulist = M('core_unit')->where($con)->select();
        $clist = M('core_class')->where($ccon)->select();
        $this->assign('ulist',$ulist);
        $this->assign('clist',$clist);
        $id =M('core_pay_bill_view')->Max('id');
        $_SESSION['batch'] =M('core_pay_bill_view')->where('id='.$id)->getField('batch');
        $map['batch'] =$_SESSION['batch'];
        $map['unit']=$_SESSION['oc_home']['unit'];
        $bill_tmp = M('core_pay_bill_view')->where($map)->group('uid')->order('id desc')->select();

            //子账单总金额
            foreach ($bill_tmp as $key => $value) {
                $bill_tmp[$key]['amount'] =      M('core_pay_bill_view')->where($map)->where('uid = '.$value['uid'])->sum('amount');
                $bill_tmp[$key]['last_amount'] = M('core_pay_bill_view')->where($map)->where('uid = '.$value['uid'])->sum('last_amount');
                $bill_tmp[$key]['amount'] = $bill_tmp[$key]['amount'] - $bill_tmp[$key]['last_amount'];
                $bill_tmp[$key]['detail'] = M('core_pay_bill_view')->where($map)->where('uid = '.$value['uid'])->getField('id,item_c,ctitle,amount',true);
            }
        $this->assign('list',$bill_tmp);
        $this->assign('ylist',$bill_tmp[0]['detail']);
        $this->display();
    }
    public function parent()
    { 
        $map['uid']=$_SESSION['oc_home']['uid'];
        $list=M('core_pay_order')->where($map)->select();
        foreach ($list as $key => $value) {
            $data=M('core_userinfo_view')->where('uid='.$value['uid'])->getField('nickname');
            $fff=M('core_userinfo_view')->where('uid='.$value['uid'])->getField('class_title');
            $list[$key]['lname']=$data;
            $list[$key]['class']=$fff;
        }
        $this->assign('list',$list);
        $this->display();
    }
    public function studentpay1()
    {
        $map['unit']=$_SESSION['oc_home']['unit'];
        $map['uid']=$_SESSION['oc_home']['uid'];
        $map['pay_state'] = 0;
        $totalCount = M('core_pay_bill_view')->where($map)->count();
        $page = new \Think\Page($totalCount,4);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list =M('core_pay_bill_view')->where($map)->limit($limit)->order('id desc')->group('uid')->select();
        $count=count($list);
        //子账单总金额
       
        foreach ($list as $key => $value) {
            $list[$key]['amount'] =      M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('amount');
            $list[$key]['last_amount'] = M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('last_amount');
            $list[$key]['amount'] = $list[$key]['amount']- $list[$key]['last_amount'];
        } 
    
     
        
        $this->assign('list',$list);
        $this->assign('dlist',$dlist);
        $this->assign('_page',$page->show());
        $this->assign('count',$count);
        
        // dump($wlist);exit;
        $this->display();
    }
    public function studentpay2()
    {
        $map['unit']=$_SESSION['oc_home']['unit'];
        $map['uid']=$_SESSION['oc_home']['uid'];
        $map['pay_state'] = 0;
        $totalCount = M('core_pay_bill_view')->where($map)->count();
        $page = new \Think\Page($totalCount,4);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list =M('core_pay_bill_view')->where($map)->limit($limit)->order('id desc')->group('uid')->select();
        $count=count($list);
        //子账单总金额
       
        foreach ($list as $key => $value) {
            $list[$key]['amount'] =      M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('amount');
            $list[$key]['last_amount'] = M('core_pay_bill_view')->where($map)->where('item = '.$value['item'])->sum('last_amount');
            $list[$key]['amount'] = $list[$key]['amount']- $list[$key]['last_amount'];
        } 
    
     
        
        $this->assign('list',$list);
        $this->assign('dlist',$dlist);
        $this->assign('_page',$page->show());
        $this->assign('count',$count);
        
        // dump($wlist);exit;
        $this->display();
    }

     public function studentorder()
    {
        // $map['uid'] = 11;
        $map['uid'] = $_SESSION['oc_home']['uid'];
        $map['unit'] = $_SESSION['oc_home']['unit'];
        $map['status'] =1;
        
        $totalCount = M('core_pay_order_view')->where($map)->count();
        $page = new \Think\Page($totalCount,5);
        $limit = $page->firstRow . ',' . $page->listRows . ',' . $page->totalRows;
        $list =M('core_pay_order')->where($map)->limit($limit)->order('id desc')->select();
        $this->assign('list',$list);
        $this->assign('_page',$page->show());
        $this->assign('count',$totalCount);   
        $this->display();
    }
    //生成订单
    public function create_order()
    {
        $data['uid'] = I('uid');
        $data['unit'] = I('unit');
        $a = explode(' ',microtime());
        $data['order_id'] = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));
        $data['order_name'] = I('order_name');
        $map['uid'] = I('uid');
        $map['unit'] = I('unit');
        $map['item'] = I('item');
        $map['pay_state'] =0;
        $detail= M('core_pay_bill_view')->where($map)->field('last_amount,ctitle,amount')->select();
       
        foreach ($detail as $key => $v) {
            $tmp .=$v['ctitle'].':'.$v['amount'].'，结余：'.$v['last_amount'].' ';
        }
   
        $data['order_detail'] = $tmp;//在这里查出来拼接明细
        $data['amount'] = I('amount');
        $data['paystate'] = 0;
        $data['status'] = 1;
        $data['create_time'] = time();
        M('core_pay_order')->add($data);
        $aaa['order_id']=$data['order_id'];
        M('core_pay_bill')->where($map)->save($aaa);
        return   $data['order_id'];

    }
    //生成流水
    public function create_flow($order_id)
    {
        $data['unit']=I('unit');
        $data['amount'] = I('amount');
        $data['order_id']=$order_id;
        $a = explode(' ',microtime());
        $data['flow_id'] = (date('ymd').'01'.substr($a[1],-5).substr($a[0]*100000000, 0,3).rand(10,99));
        $data['create_time']=time();
        $data['paystate']=0;
        $data['state']=1;
        M('core_pay_flow')->add($data);
         return   $data['flow_id'];
    }
    //去支付
    public function pay()
    {       
        header("Content-type: text/html; charset=utf-8");
        $a=$this->create_order();
        

        $MERCHANTID='MYGS0218100254';// 商户编号

        $POSID = '10001010'; // 商户柜台代码

        $ORDERID= $this->create_flow($a); // 支付流水号
        $PROINFO= $this->escape('账单'); // 商品信息

        $PAYMENT = I('amount'); // 付款金额

        $REMARK1 = $this->escape("优惠活动"); // 备注一
        $LINKTYPE =2; // 客户端接入方式
        //----传输信息-------------
        $PERKEY = 'zibodake'; //私钥

        $dopayURL="http://dopay.epayol.com/index.php/Home/Dopay/pay";
        //发送字符串
        $postMsg='MERCHANTID='.$MERCHANTID.'&POSID='.$POSID.'&ORDERID='.$ORDERID.'&PROINFO='.$PROINFO.'&PAYMENT='.$PAYMENT.'&REMARK1='.$REMARK1.'&PAYIP='.get_client_ip().'&LINKTYPE='.$LINKTYPE;    

        $URL = $dopayURL . '?' .$postMsg. '&SIGN=' . MD5 ($postMsg . '&PERKEY=' . $PERKEY) ;
        header("Location:".$URL);
    }        


    //PC端分院长导入学生
     public function impor()
    {
        //上传xls
     if(IS_POST){
        $upload = new UploadFile();// 实例化上传类
        $upload->maxSize  = 3145728 ;// 设置附件上传大小
        $upload->allowExts  = array('xls','xlsx');// 设置附件上传类型
        if (!file_exists('./Uploads/Data/'.date('Ymd').'/')){ 
            mkdir('./Uploadsi/Data/'.date('Ymd').'/'); 
        }
        $upload->savePath =  './Uploads/Data/'.date('Ymd').'/';// 设置附件上传目录
        if(!$info = $upload->upload()) {// 上传错误提示错误信息
            $this->error($upload->getErrorMsg());
        }else{// 上传成功 获取上传文件信息
            $info =  $upload->getUploadFileInfo();
        }
        $info[0]['savepath']=substr($info[0]['savepath'], 1); 
        $filename = $info[0]['savepath'].$info[0]['savename'];
        $para = $_SESSION['oc_home']['unit']; //同时获取地区id和单位id，分别生成达客id和外键用
        //$para['group'] = I('group');
        dump($info);
        dump($filename);
        dump($_SESSION);
        $batch = $this->UshowExcel($filename,$para);
        $this->success('成功,正在跳转……');//导入成功
     }
        
      
    }
    // //预览
    // public function yulan()
    // {   

    //     $tmpModel = M('core_data');
    //     if(IS_POST){
    //         $tmp = $tmpModel->where("batch = '".I('batch')."'")->select();
    //         if($this->dataModel->addAll($tmp)){$this->success('导入成功',U('Data/index'));}else{$this->error('导入失败');}
    //     }else{
    //         $list = $tmpModel->where("batch = '".I('batch')."'")->order('dkyey_core_data_tmp.id desc')->join('dkyey_core_unit ON dkyey_core_data_tmp.unit = dkyey_core_unit.id')->field('dkyey_core_unit.title,dkyey_core_data_tmp.realname,dkyey_core_data_tmp.depart,dkyey_core_data_tmp.batch,dkyey_core_data_tmp.id')->select();
    //         $this->assign('_list',$list);
    //         $this->display(self::MODEL_NAME.'Data/yulan');
    //     }
    // }

    //数据管理-因为导入的文件，所以需要一个文件类来打开该文件
    public function UshowExcel($filename,$para)
    {
        header('Content-type:text/html;charset=utf8');
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Reader.Excel5");
        //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
        //创建PHPExcel对象，注意，不能少了\
        $PHPExcel=new \PHPExcel();
        //如果excel文件后缀名为.xls，导入这个类
        import("Org.Util.PHPExcel.Reader.Excel2007");
        $PHPReader=new \PHPExcel_Reader_Excel5();
        //载入文件
        $PHPExcel=$PHPReader->load('.'.$filename);
        //获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
        $currentSheet=$PHPExcel->getSheet(0);
        //获取总列数
        $allColumn=$currentSheet->getHighestColumn();
        //获取总行数
        $allRow=$currentSheet->getHighestRow();
        //循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
        for($currentRow=2;$currentRow<=$allRow;$currentRow++){
            //从哪列开始，A表示第一列
            for($currentColumn='A';$currentColumn<=$allColumn;$currentColumn++){
                //数据坐标
                $address=$currentColumn.$currentRow;
                //读取到的数据，保存到数组$arr中
                $arr[$currentRow][$currentColumn]=$currentSheet->getCell($address)->getValue();
            }
        }
        /////存入临时表
        $TempModel = D('core_data');
        $batch = md5($filename);
        foreach ($arr as $key => $value) {
            $dksign = $this->getDKsign($para);
            $data = array(  
                  'realname'=>(string)trim($value['A']),
                  'depart'=>(string)trim($value['B']),
                  'group'=>(string)trim($value['C']),
                  'unit'=>$para,
                  'status'=>1,
                  'create_time'=>time(),
                  'dksign'=>$dksign,
                  'batch'=>$batch,
                  );
            $tmp[] = $data;
        }
        if($TempModel->addAll($tmp)){
            return $batch;//返回批次号，便于查找。
        }else{
            echo "导入失败";
        }
    }

    //获得达客id
    public function getDKsign($unit)
    {
        $d['dksign'] = create_DKsign('ns',$unit);
        $d['create_time'] = time();
        $result = M('core_dksign')->add($d);
        if(!$result) {
            getDKsign($unit);
        }
        return $d['dksign'];
    }

 // --json传送中文字符串的加密编码escape函数

    function escape($str) {

        preg_match_all ( "/[\xc2-\xdf][\x80-\xbf]+|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}|[\x01-\x7f]+/e", $str, $r );

        // 匹配utf-8字符，

        $str = $r [0];

        $l = count ( $str );

        for($i = 0; $i < $l; $i ++) {

            $value = ord ( $str [$i] [0] );

            if ($value < 223) {

                $str [$i] = rawurlencode ( utf8_decode ( $str [$i] ) );

                // 先将utf8编码转换为ISO-8859-1编码的单字节字符，urlencode单字节字符.

                // utf8_decode()的作用相当于iconv("UTF-8","CP1252",$v)。

            } else {

                $str [$i] = "%u" . strtoupper ( bin2hex ( iconv ( "UTF-8", "UCS-2", $str [$i] ) ) );

            }

        }

        return join ( "", $str );

    }
   
}